package com.yupi.springbootinit.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.OrderMapper;
import com.yupi.springbootinit.model.dto.order.OrderAddRequest;
import com.yupi.springbootinit.model.entity.Book;
import com.yupi.springbootinit.model.entity.Order;
import com.yupi.springbootinit.model.vo.OrderVo;
import com.yupi.springbootinit.service.BookService;
import com.yupi.springbootinit.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

import static com.yupi.springbootinit.constant.RabbitMqConstant.ORDER_SUBMIT_EXCHANGE;
import static com.yupi.springbootinit.constant.RabbitMqConstant.ORDER_SUBMIT_ROUTE_KEY;

/**
* @author wzhRoot
* @description 针对表【order】的数据库操作Service实现
* @createDate 2023-12-16 16:10:41
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService {
    @Resource
    private BookService bookService;


    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public OrderVo addOrder(OrderAddRequest orderAddRequest) {
//        todo 校验商品和用户是否存在
/*        Long userId = orderAddRequest.getUserId();*/
        Integer bookNum = orderAddRequest.getBookNum();
        Double charging = orderAddRequest.getCharging();
        Double shioppingCost = orderAddRequest.getShioppingCost();
        BigDecimal totalAmount = orderAddRequest.getTotalAmount();
        totalAmount=totalAmount.divide(new BigDecimal(100));

        Integer bookId = orderAddRequest.getBookId();
        // 后端校验订单总价格
        double temp = charging * bookNum+shioppingCost;
        BigDecimal bd=new BigDecimal(temp);
        double finalPrice = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if (finalPrice != totalAmount.doubleValue()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "价格错误");
        }

       //判断库存是否足够
        Integer inventory = bookService.getById(bookId).getInventory();
        if (inventory<=0||inventory-bookNum<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"库存不足");
         }
        //扣减库存
       if (!updateStock(bookId, bookNum)){
           throw new BusinessException(ErrorCode.SYSTEM_ERROR,"扣减库存失败");
       }
         //保存订单数据
        Order order=new Order();
        String orderNum = generateOrderNum(RandomUtil.randomLong());
        order.setOrderNo(orderNum);
        order.setBookAllPrice(finalPrice);
        order.setCreateTime(new Date());
        BeanUtils.copyProperties(orderAddRequest, order);
        order.setOrderStatus(0);
        order.setOrderMoney(0.0);
        order.setPayChannel(1);
        this.save(order);
       //消息队列发送延时消息
        rabbitTemplate.convertAndSend(ORDER_SUBMIT_EXCHANGE,ORDER_SUBMIT_ROUTE_KEY,order);
        // todo 6. 构造订单详情并回显
        OrderVo orderVo=new OrderVo();
        BeanUtil.copyProperties(order,orderVo);
        return orderVo;
    }

    @Override
    public boolean recoverInterfaceStock(Integer bookId, Integer bookNum) {
        UpdateWrapper<Book> updateWrapper=new UpdateWrapper<>();
        updateWrapper.setSql("inventory = inventory + "+bookNum)
                .eq("id",bookId).gt("inventory",bookNum);
        return bookService.update(updateWrapper);
    }


    private boolean updateStock(Integer bookId,Integer num){
    UpdateWrapper<Book> updateWrapper=new UpdateWrapper<>();
    updateWrapper.setSql("inventory = inventory - "+num)
            .eq("id",bookId).gt("inventory",num);
   return bookService.update(updateWrapper);
}


    private String generateOrderNum(Long userId) {
        String timeId = IdWorker.getTimeId();
        String substring = timeId.substring(0, timeId.length() - 15);
        return substring + RandomUtil.randomNumbers(5) + userId;
    }


}



